package com.example.provider.service


import com.example.common.entity.UserDubbo
import com.example.common.exception.DemoException
import com.example.common.service.UserDubboService
import com.example.provider.db.mongodb.model.User
import com.example.provider.db.mongodb.model.UserLog
import com.example.provider.db.mongodb.repository.UserLogRepository
import com.example.provider.db.mongodb.repository.UserRepository
import org.apache.dubbo.config.annotation.DubboService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional


@DubboService
open class UserServiceImpl : UserDubboService {
    @Autowired
    lateinit var userRepository: UserRepository

    @Autowired
    lateinit var userLogRepository: UserLogRepository


    override fun list(): List<UserDubbo> {
        val list = userRepository.findAll()
        return list.map { UserDubbo(it.id, it.name, it.email) }
    }

    override fun getById(id: String): UserDubbo {
        val u = userRepository.getById(id).orElse(null)
        val res = UserDubbo(u?.id, u?.name, u?.email)
        return res
    }

    //    @Transactional("mongoTransactionManager")
    override fun create(item: UserDubbo) {
        val u = userRepository.getById(item.id)
        if (u.isPresent) {
            throw DemoException("user id is  exist")
        }
        userRepository.save(User(item.id, item.name, item.email))
        userLogRepository.insert(UserLog(null, "create $item"))
    }

    //    @Transactional("mongoTransactionManager")
    override fun update(item: UserDubbo) {
        val u = userRepository.getById(item.id)
        if (!u.isPresent) {
            throw DemoException("user is not exist")
        }
        userRepository.save(User(item.id, item.name, item.email))
        userLogRepository.insert(UserLog(null, "update id:${item.id} to $item"))
    }

    //    @Transactional("mongoTransactionManager")
    override fun delete(id: String) {
        userRepository.deleteById(id)
        userLogRepository.insert(UserLog(null, "delete id:$id"))
    }


}